package pkg

import (
	"TaskAssignmentSystem/pkg/utils"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"reflect"
	"sort"
)

func VerifySign(ctx iris.Context) {
	body, _ := ctx.GetBody()
	var RequestParams map[string]interface{}
	err := json.Unmarshal(body, &RequestParams)
	if err != nil {
		ctx.JSON(iris.Map{"code": 40001, "message": "签名有误"})
		return
	}
	var keys []string
	for k, v := range RequestParams {
		if k != "sign" {
			typeOfA := reflect.TypeOf(v)
			keys = append(keys, k)
			if typeOfA != nil && typeOfA.Kind() != reflect.String {
				bytes, _ := json.Marshal(v)
				RequestParams[k] = string(bytes) //strings.Replace(string(bytes), "\"", "", -1 )
			}
		} else {
			continue
		}
	}
	//对key排序
	sort.Strings(keys)
	var paramString string
	for _, k := range keys {
		paramString += fmt.Sprintf("&%s=%s", k, RequestParams[k])
	}
	signStr := fmt.Sprintf("appkey=%s%s", "", paramString)
	sign := utils.MD5(signStr)
	if sign != RequestParams["sign"] {
		ctx.JSON(iris.Map{"code": 40001, "message": "签名有误"})
		return
	} else {
		ctx.Next()
	}
}
